package com.cy.service.impl;

import com.cy.common.annotation.RequiredLog;
import com.cy.common.untils.PageUtil;
import com.cy.dao.SysUserDao;
import com.cy.dao.SysUserRoleDao;
import com.cy.pojo.SysUser;
import com.cy.service.SysUserService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @RequiresPermissions("sys:user:update")
    @Override
    public PageInfo<List<SysUser>> selectSysUser(String username) {
        PageInfo<List<SysUser>> objectPageInfo = PageUtil.startPage()
                .doSelectPageInfo(() -> sysUserDao.selectSysUser(username));
        return objectPageInfo;
    }

    @Override
    public int userDisable(Integer id, Integer valid, String modifiedUser) {
        return sysUserDao.userDisable(id,valid,modifiedUser);
    }

    @Override
    public SysUser selectById(Integer id) {
        SysUser sysUser = sysUserDao.selectById(id);
        List<Integer> roleIds = sysUserRoleDao.selectRoleIdsByUserId(id);
        sysUser.setRoleIds(roleIds);
        return sysUser;
    }

    @Transactional(timeout = 5)
    @Override
    public int updateUser(SysUser sysUser) {
        int row = sysUserDao.updateUser(sysUser);
        sysUserRoleDao.deleteByUserId(sysUser.getId());
        sysUserRoleDao.insertUserRole(sysUser.getId(), sysUser.getRoleIds());
        return row;
    }

    @Override
    public int insertUser(SysUser sysUser) {
        //产生一个随机字符串作为加密盐使用
        String salt= UUID.randomUUID().toString();
        //对密码进行 MD5 盐值加密(MD5 特点:不可逆,相同内容加密结果也相同)
        SimpleHash sh=new SimpleHash("MD5",sysUser.getPassword(),salt,1);
        String hashedPassword=sh.toHex();
        sysUser.setSalt(salt);
        sysUser.setPassword(hashedPassword);
        int row = sysUserDao.insertUser(sysUser);
        sysUserRoleDao.insertUserRole(sysUser.getId(), sysUser.getRoleIds());
        return row;
    }
}
